package org.zjx.command.composite;

import org.zjx.command.Command;
import org.zjx.command.CompositeCommand;
import org.zjx.core.GameWindow;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 增强的复合指令（支持动态插入）
 */
public abstract class DynamicCompositeCommand extends CompositeCommand {
    protected final List<Command> pendingCommands = new CopyOnWriteArrayList<>();
    protected int currentIndex = 0;
    protected boolean executing = false;

    public DynamicCompositeCommand(GameWindow window, String name) {
        super(window, name);
    }

    /**
     * 重写执行逻辑，支持动态插入
     */
    @Override
    protected void doExecute() {
        executing = true;
        currentIndex = 0;

        System.out.println("[DynamicComposite] Starting execution: " + getCommandName());

        // 执行主命令列表
        while (currentIndex < subCommands.size() && !Thread.currentThread().isInterrupted()) {
            executeNextCommand();
        }

        // 执行待处理命令（动态插入的）
        while (!pendingCommands.isEmpty() && !Thread.currentThread().isInterrupted()) {
            executePendingCommand();
        }

        executing = false;
        System.out.println("[DynamicComposite] Completed: " + getCommandName());
    }

    /**
     * 执行下一个主命令
     */
    protected void executeNextCommand() {
        if (currentIndex < subCommands.size()) {
            Command cmd = subCommands.get(currentIndex);
            System.out.println("[DynamicComposite] Executing main command " + (currentIndex+1) + "/" +
                    subCommands.size() + ": " + cmd.getCommandName());
            cmd.execute();
            currentIndex++;
        }
    }

    /**
     * 执行待处理命令
     */
    protected void executePendingCommand() {
        if (!pendingCommands.isEmpty()) {
            Command cmd = pendingCommands.remove(0);
            System.out.println("[DynamicComposite] Executing pending command: " + cmd.getCommandName());
            cmd.execute();
        }
    }

    /**
     * 在当前执行位置之后插入命令
     */
    public void insertCommandAfterCurrent(Command command) {
        if (command != null && command.getTargetWindow() == this.targetWindow) {
            if (executing) {
                // 如果正在执行，插入到待处理队列
                pendingCommands.add(command);
                System.out.println("[DynamicComposite] Inserted pending command: " + command.getCommandName());
            } else {
                // 如果未开始执行，插入到主列表
                subCommands.add(currentIndex, command);
                System.out.println("[DynamicComposite] Inserted main command at index " + currentIndex +
                        ": " + command.getCommandName());
            }
        }
    }

    /**
     * 在指定位置插入命令
     */
    public void insertCommandAt(int index, Command command) {
        if (command != null && index >= 0 && index <= subCommands.size()) {
            subCommands.add(index, command);
            System.out.println("[DynamicComposite] Inserted command at index " + index +
                    ": " + command.getCommandName());
        }
    }

    /**
     * 添加命令到末尾
     */
    public void addCommandToEnd(Command command) {
        if (command != null) {
            subCommands.add(command);
            System.out.println("[DynamicComposite] Added command to end: " + command.getCommandName());
        }
    }

    /**
     * 获取当前执行状态
     */
    public String getExecutionState() {
        return String.format("Main: %d/%d, Pending: %d",
                currentIndex, subCommands.size(), pendingCommands.size());
    }
}